<template>
  <n-tree-select
    v-if="options && options.length"
    :options="options"
    @update:value="handleUpdateValue"
    :value="modelValue"
    clearable
    filterable
    :default-expanded-keys="expandKeys"
  />
  <n-tree-select v-else :options="[]" @update:value="handleUpdateValue" clearable filterable />
</template>

<script setup lang="ts" name="NAreaSelect">
import { TreeSelectOption } from 'naive-ui';
import { computed, ref, watch } from 'vue';
import { useArea } from '@/hooks/userArea';

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  address: {
    type: String,
    default: '',
  },
  topAreaCode: {
    type: String,
  },
});
const emits = defineEmits(['update:modelValue', 'update:address']);

const { areaData, getAddressByCode, getAreaSelectList } = useArea();

const options = computed<TreeSelectOption[]>(() => getAreaSelectList(props.topAreaCode));

const expandKeys = computed(() =>
  options.value && options.value.length === 1 ? [options.value[0].key] : []
);
function handleUpdateValue(value: string) {
  //   console.log(value, getAddressByCode(value));
  emits('update:modelValue', value);
  emits('update:address', getAddressByCode(value));
}
watch(
  () => props.modelValue,
  (val) => {
    val && emits('update:address', getAddressByCode(val));
  }
);
</script>

<style scoped>
</style>